#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
    int pipe_fd[2] ={0};
    if(pipe(pipe_fd) < 0)
        printf("管道创建失败\n");
    //printf("%d %d\n",pipe_fd[0],pipe_fd[1]);
    int id = fork();
    //子进程写，父进程读为例
    //pipe_fd[0]是读取  pipe_fd[1]是写入
    if(id == 0)
    {
        //child
        close(pipe_fd[0]);
        // int count = 0;
        while(1)
        {
            
            // const char* ch = "a";
            const char* msg = "hello Mango";
            write(pipe_fd[1],msg,strlen(msg));
            // count++;
            // printf("count:%d\n",count);
            // sleep(5);
            // break;
        }
        close(pipe_fd[1]);
    }
    //parent
    close(pipe_fd[1]);
    while(1)
    {
        char buffer[1024] = {0};
        ssize_t n = read(pipe_fd[0],buffer,sizeof(buffer)-1);
        if(n == 0 ) //写端关闭
        {
            printf("写端关闭.....\n");
            break;
        }
        else if(n < 0)
        {
            printf("读取出错\n");
            break;
        }
        else
        {
            buffer[n] = 0;
            printf("读取到的内容为：%s\n",buffer);
        }
        sleep(5);
        break;
    }
    close(pipe_fd[0]);
    int status = 0;
    pid_t res = waitpid(id,&status,0);
    if(res > 0)
    {
        printf("子进程退出码:%d 收到的信号：%d\n",(status>>8)&0xff,status&0x7f);
    }
    return 0;
}